<script setup>
import Message from 'vue-m-message'
import { getConfigKey } from '@/api/system/config.js'
import FileUpload from '@/components/FileUpload/index.vue'
import ossService from '@/api/oss/index.js'
import Toolbar from '@/components/Toolbar/Toolbar.vue'
import downloadUtils from '@/utils/download.js'
import { deepClone, tableCheckChane } from '@/utils/index.js'

const { proxy } = getCurrentInstance()
const pagerConfig = ref({
  total: 0,
  currentPage: 1,
  pageSize: 10,
})
const ids = ref([])
const tableData = ref([])
const tableColumn = reactive([
  {
    type: 'checkbox',
    width: 50,
    align: 'center',
  },
  { title: '对象存储主键', field: 'ossId', align: 'center' },
  { title: '文件名', field: 'fileName', align: 'center' },
  { title: '原名', field: 'originalName', align: 'center' },
  { title: '文件后缀', field: 'fileSuffix', align: 'center' },
  { title: '文件展示', field: 'url', align: 'center',
    slots: {
      default: 'url',
    },
  },
  { title: '创建时间', field: 'createTime', align: 'center' },
  { title: '上传人', field: 'createBy', align: 'center' },
  { title: '服务商', field: 'service', align: 'center' },
  {
    title: '操作',
    align: 'center',
    field: 'action',
    slots: {
      default: 'actions',
    },
  },
])
const searchConfig = reactive([
  {
    label: '文件名',
    field: 'fileName',
    type: 'input',
    defaultShow: true,
  },
  {
    label: '原名',
    field: 'originalName',
    type: 'input',
    defaultShow: true,

  },
  {
    label: '文件后缀',
    field: 'fileSuffix',
    type: 'input',
    defaultShow: true,

  },
  {
    label: '创建时间',
    field: 'createTime',
    type: 'daterange',
    defaultShow: true,

  },
  {
    label: '上传人',
    field: 'createBy',
    type: 'input',
  },
  {
    label: '服务商',
    field: 'service',
    type: 'input',
  },
])
const queryParam = ref({})
const imgFileList = ['.png', '.jpg', '.jpeg', '.gif', '.svg', '.webp', '.ico']
const fileUploadVisible = ref(false)
const uploadFile = ref([])
onMounted(() => {
  getList()
})

function getList() {
  const params = {
    ...queryParam.value,
    pageNum: pagerConfig.value.currentPage,
    pageSize: pagerConfig.value.pageSize,
  }
  ossService.list(params).then((res) => {
    if (res.code === 200) {
      tableData.value = res.rows
      pagerConfig.value.total = res.total
    }
  })
}

function handleAdd() {
  fileUploadVisible.value = true
}

function handleDelete(id) {
  const delId = id || ids.value.join(',')
  ossService.delete(delId).then((res) => {
    if (res.code === 200) {
      Message.success('删除成功')
      getList()
    }
  })
}
function handlePageChange({ currentPage, pageSize }) {
  pagerConfig.value.currentPage = currentPage
  pagerConfig.value.pageSize = pageSize
  getList()
}

function handleCheckChange(data) {
  ids.value = tableCheckChane(data, 'ossId', ids.value)
}

function handleExport() {
  proxy.download('', { ...queryParam.value, exportIds: ids.value.join(',') }, `_${new Date().getTime()}.xlsx`)
}

function handleSearch(params) {
  queryParam.value = {
    ...deepClone(params),
    'params["beginCreateTime"]': params.createTime?.[0],
    'params["endCreateTime"]': params.createTime?.[1],
  }
  delete queryParam.value.createTime
  pagerConfig.value.currentPage = 1
  getList()
}
function handleDownload(row) {
  downloadUtils.ossDownload(row.ossId)
  Message.success('成功下载')
}

function handleUploadSubmit() {
  getConfigKey('sys.oss.previewListResource').then((res) => {
    const code = res.code
    if (code === 200) {
      getList()
      fileUploadVisible.value = false
    }
  })
}
</script>

<template>
  <div class="app-container">
    <el-card shadow="never" class="">
      <SearchBar :search-config="searchConfig" @search="handleSearch" />
    </el-card>
    <el-card shadow="never" class="mt-2">
      <Toolbar>
        <el-button
          v-hasPermi="['system:oss:add']"
          type="primary"
          class="el-gradient-primary"
          @click="handleAdd"
        >
          上传文件
          <el-icon class="el-icon--right">
            <CirclePlusFilled />
          </el-icon>
        </el-button>
        <el-button
          v-hasPermi="['system:oss:remove']"
          type="danger"
          class="el-gradient-danger"
          :disabled="ids.length === 0"
          @click="handleDelete(null)"
        >
          删除
          <el-icon class="el-icon--right">
            <Delete />
          </el-icon>
        </el-button>
      </Toolbar>
      <vxe-grid
        :row-config="{
          keyField: 'ossId',
        }"
        :data="tableData"
        :columns="tableColumn"
        :pager-config="pagerConfig"
        header-cell-class-name="headerCellClass"
        height="650px"
        @page-change="handlePageChange"
        @checkbox-all="handleCheckChange"
        @checkbox-change="handleCheckChange"
      >
        <template #url="{ row }">
          <el-image
            v-if="imgFileList.includes(row.fileSuffix)" :src="row.url" fit="cover"
            :preview-src-list="[row.url]"
          />
          <el-link v-else :href="row.url" target="_blank">
            {{ row.originalName }}
          </el-link>
        </template>
        <template #actions="{ row }">
          <el-button
            v-hasPermi="['system:oss:download']"
            size="small"
            type="primary"
            text
            @click="handleDownload(row)"
          >
            下载
          </el-button>
          <span v-hasPermi="['system:oss:remove']">
            <el-popconfirm
              title="确认删除该文件？"
              @confirm="() => handleDelete(row.ossId)"
            >
              <template #reference>
                <el-button size="small" type="danger" text>
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </span>
        </template>
      </vxe-grid>
    </el-card>
    <el-dialog
      v-model="fileUploadVisible"
      class="custom-dialog"
      width="30%"
    >
      <template #header>
        <div class="dialog-header">
          <span class="relative top-3 text-[16px]">
            上传文件
          </span>
        </div>
      </template>
      <FileUpload :file-type="[]" />
      <template #footer>
        <div class="px-2 py-3">
          <el-button plain @click="fileUploadVisible = false">
            取消
          </el-button>
          <el-button type="primary" @click="handleUploadSubmit">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>

</style>
